package com.security2.demo.security;

import com.security2.demo.authentication.AuthLimitHandler;
import com.security2.demo.utils.SecurityConstants;
import com.security2.demo.authentication.AuthenticationFailureHandler;
import com.security2.demo.authentication.AuthenticationSuccessHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

/**
 * 自定义安全策略
 */
@Configuration
public class BrowserSecurityConfig extends WebSecurityConfigurerAdapter {
    //登录成功处理
    @Autowired
    private AuthenticationFailureHandler authenticationFailureHandler;
    //登录失败处理
    @Autowired
    private AuthenticationSuccessHandler authenticationSuccessHandler;
    //退出处理
    @Autowired
    private LogoutSuccessHandler logoutSuccessHandler;
    //权限不足处理器
    @Autowired
    private AuthLimitHandler authLimitHandler;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //安全配置
        http.formLogin()
                .loginPage(SecurityConstants.DEFAULT_UNAUTHENTICATION_URL)//访问的资源需要认证处理逻辑
                .loginProcessingUrl(SecurityConstants.DEFAULT_LOGIN_PROCESSING_URL_FORM)//登录地址
                .successHandler(authenticationSuccessHandler)
                .failureHandler(authenticationFailureHandler)

                //权限控制
                .and()
                .authorizeRequests()
                .antMatchers(HttpMethod.GET, "/user/*")
                .access("hasRole('ADMIN')")
                //不需要拦截
                .antMatchers(SecurityConstants.DEFAULT_UNAUTHENTICATION_URL,
                        SecurityConstants.DEFAULT_VALIDATE_CODE_URL_PREFIX + "/*",
                        SecurityConstants.DEFAULT_SESSION_INVALID_URL)
                .permitAll()
                .anyRequest()
                .authenticated()

                //退出操作
                .and()
                .logout()
                .logoutUrl("/signOut")
                .logoutSuccessHandler(logoutSuccessHandler)
                .deleteCookies("JSESSIONID");

        // 用户权限不足处理器
        http.exceptionHandling().accessDeniedHandler(authLimitHandler);


        //攻击防护: 关闭
        http.csrf().disable();
    }
}
